
package com.ifcar.app.activity.common;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView.RecyclerListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ifcar.app.activity.AccountLogin;
import com.ifcar.app.activity.BaseActivity;
import com.ifcar.app.activity.CollectActivity;
import com.ifcar.app.activity.MyCommentsActivity;
import com.ifcar.app.activity.common.CommonReply.ActionCallback;
import com.ifcar.app.activity.newspage.NewsFragment;
import com.ifcar.app.adapter.CommonCommentAdapter;
import com.ifcar.app.db.DBUtils;
import com.ifcar.app.db.NewsSQLiteOpenHelper;
import com.ifcar.app.fragment.NRLoadingListFrament;
import com.ifcar.app.model.Comment;
import com.ifcar.app.model.HotComment;
import com.ifcar.app.model.LatestComment;
import com.ifcar.app.model.Videos;
import com.ifcar.app.rss.GetComments;
import com.ifcar.app.util.CollectUtil;
import com.ifcar.app.util.ModelUtils;
import com.ifcar.app.util.ShareUtil;
import com.ifcar.app.util.StringUtil;
import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.util.Tools;
import com.ifcar.app.util.GroupAdapter.ItemPosition;
import com.ifcar.app.view.CommentToolsPopup;
import com.ifcar.app.view.FloorsView;
import com.ifcar.app.view.FloorsView.FloorViewHolder;
import com.ifcar.app.activity.R;
import com.netease.util.Pair;

/**
 * 跟帖模块<br/>
 * 
 * @author wjying
 */
public class CommentFragment extends NRLoadingListFrament implements OnClickListener,
        OnItemClickListener, OnTouchListener, ActionCallback , RecyclerListener{
    public static final String RERFESH_TAG = "comment_refresh";

    public static final String PARAM_COMMENT = "comment_param";
    
    /**
     * 跟帖类型如果不为空,会更新跟帖数据是否已读
     */
    public static final String COMMENT_TYPE = "comment_type";
    
    public static final String BOARD_ID = "boardid";

    public static final String COLLECT_TYPE = "collect_type";

    /**
     * 如果是图集对应图集id
     */
    public static final String DOC_ID = "docid";

    /**
     * 如果是图集对应图集名称
     */
    public static final String DOC_TITLE = "docTitle";

    public static final String COMMENT_URL = "commentUrl";

    /**
     * 在精彩跟帖有用到
     */
    public static final String TOP_P = "top_p";

    public static final String TAG_HOT = "hot";
    
    public static final String TAG_TOP = "top";

    public static final String TAG_LATEST = "latest";

    private ListView mListView;

    private List<Pair<String, List<Map<String, Object>>>> mData;

    private CommonCommentAdapter mAdapter;

    private String mBoardId;

    private String mDocId;

    private String mDocTitle;

    private int mCollectType = CollectUtil.COLLECT_COMMENT;

    private String mCommentUrl;

    private String mTopP;

    private CommentToolsPopup mToolPopup;

    private int mToolPopupX;

    private int mToolPopupY;

    private CommentTask mCommentTask;

    private CollectUtil mCollectUtil;

    private int mCommentCollectId = -1;

    private CommonReply mCommonReply;

    private ReplyCommentTask mReplyCommentTask;

    private ProgressDialog mProgressDialog;

    private float mTextSize;

    private CommentCallback mCallback;
    
    private String mCommentType;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRefreshTag(RERFESH_TAG);
        mCollectUtil = new CollectUtil(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.common_comment_layout, container, false);
    }

    @Override
    public void onViewCreatedNR(View view, Bundle savedInstanceState) {
        super.onViewCreatedNR(view, savedInstanceState);
        mListView = getListView();
        setLoadingNum(10);

        View replyFrame = view.findViewById(R.id.reply_frame);
        mCommonReply = new CommonReply(getActivity(), replyFrame);
        mCommonReply.setCallback(this);

        mListView.setOnTouchListener(this);
        mListView.setOnItemClickListener(this);
        setNRMenu(R.layout.common_comment_menu, new int[] {
                R.id.menu_refresh, R.id.menu_my_comment, R.id.menu_my_collect
        });
    }
    

    @Override
    public void onMenuClick(int id) {
        super.onMenuClick(id);
        switch (id) {
            case R.id.menu_refresh:
                refresh();
                break;
            case R.id.menu_my_comment: {
                Intent intent = new Intent(getActivity(), MyCommentsActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.menu_my_collect: {
                Intent intent = new Intent(getActivity(), CollectActivity.class);
                startActivity(intent);
                break;
            }
            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
        dismissProgressDialog();
        dismissToolPopup();

        StringUtil.clearRefreshTime(getActivity(), CommentFragment.RERFESH_TAG);
        if(null!=mData) {
            mData.clear();
            mData = null;
        }
        if(null!=mListView){
            mListView.setAdapter(null);
            mListView = null;
        }
        if(null!=mAdapter){
            mAdapter = null;
        }
    }
    
    @Override
    public boolean isMoreViewShow() {
        return false;
    }

    @Override
	public ListAdapter getAdapter() {
		return mAdapter;
	}

    private void dismissProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void dismissToolPopup() {
        if (mToolPopup != null && mToolPopup.isShowing()) {
            mToolPopup.dismiss();
        }
    }
    
    @Override
    public void onMovedToScrapHeap(View view) {
        if (view instanceof FloorsView) {
            FloorsView floors = (FloorsView) view;
            FloorViewHolder holder = floors.getFloorViewHolder();
            if (holder != null) {
                holder.recycleFloorView(floors);
            }
        }
    }
    
    

    @Override
    public void onResume() {
        super.onResume();
        float currentTextSize = NewsFragment.getTextSize(getActivity());
        if (mTextSize != currentTextSize) {
            setTextSize(currentTextSize);
        }
    }

    @Override
    public void onTabSelected(boolean first) {
        updateComment(first);

        // getListView().setAdapter(mAdapter);
        if (first) {
            setTitle(R.string.main_title_comment);
        }

        if (checkLoadingProgress()) {
            showProgress();
        } else {
            hideProgress();
        }

    }

    private void cancelTask() {
        if (mCommentTask != null && !mCommentTask.isCancelled()) {
            mCommentTask.cancel(true);
        }
        mCommentTask = null;
    }

    /**
     * 根据arguments中的参数变化更新comment列表
     */
    private void updateComment(boolean first) {
        Bundle b = getArguments() != null ? getArguments().getBundle(PARAM_COMMENT) : null;
        if (b == null) {
            b = getArguments();
        }
        if (b == null) {
            return;
        }
        
        String boardid = b.getString(BOARD_ID);
        String docid = b.getString(DOC_ID);
        String docTitle = b.getString(DOC_TITLE);
        String commentUrl = b.getString(COMMENT_URL);
        boolean isfromVideo = b.getBoolean(Videos.IS_FROM_VIDEO);
        if(isfromVideo) mCommonReply.setCollectVisiabled(false);
        if (TextUtils.isEmpty(mBoardId) || !mBoardId.equals(boardid) || TextUtils.isEmpty(mDocId)
                || !mDocId.equals(docid)) {
            
            mBoardId = boardid;
            mDocId = docid;
            mDocTitle = docTitle;
            mCommentUrl = commentUrl;
            mCollectType = b.getInt(COLLECT_TYPE, CollectUtil.COLLECT_COMMENT);
            mTopP = b.getString(TOP_P);

            mCommentCollectId = -1;

            if (!TextUtils.isEmpty(mCommentUrl)) {
                mCommentCollectId = mCollectUtil.getAlreadyCollect(mCommentUrl, "1", mCollectType);
            } else {
                mCommonReply.setCollectEnabled(false);
                mCommonReply.setCollectVisiabled(false);
            }
            
            mCommonReply.setCollected(mCommentCollectId != -1);
            
            mCommentType = b.getString(COMMENT_TYPE);
            if (!TextUtils.isEmpty(mCommentType)) {
                final SQLiteDatabase db = getDb();
                final String doc_id = mDocId;
                final String column = mCommentType;
                setCallback(new CommentCallback() {                    
                    @Override
                    public void onCommentRefreshed(CommentFragment fragment, boolean successed) {                       
                        String sql = "select * from " + NewsSQLiteOpenHelper.ARTICLE_READ_LIST_TABLE + 
                        " where " + NewsSQLiteOpenHelper.ARTICLE_READ_DOC_ID + "=? and " + NewsSQLiteOpenHelper.ARTICLE_READ_COL_ID + "=?";
                        try {
                            Cursor cursor = db.rawQuery(sql, new String[]{doc_id, column});
                            if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
                                ContentValues initialValues = new ContentValues();
                                initialValues.put(NewsSQLiteOpenHelper.ARTICLE_READ_STATUS, "Y");   
                                db.update(NewsSQLiteOpenHelper.ARTICLE_READ_LIST_TABLE, initialValues, "article_read_doc_id=?", new String[]{doc_id});   
                            } else {            
                                DBUtils.insertDataToReadStatusTable(db, doc_id, column, "Y");
                            }
                            cursor.close();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        
                    }
                });
            } else {
                setCallback(null);
            }

            cancelTask();

            mAdapter = null;

            getLoadingListView().reset();

            if (mListView != null) {
                mListView.setAdapter(null);
            }

            refresh();
        } else if (isNeedRefresh()) {
            cancelTask();
            getHandler().post(new Runnable() {
                @Override
                public void run() {
                    refresh();
                }
            });
        }
        
        float currentTextSize = NewsFragment.getTextSize(getActivity());
        if (mTextSize != currentTextSize) {
            setTextSize(currentTextSize);
        }
    }

    public void setCallback(CommentCallback callback) {
        mCallback = callback;
    }

    public void setTextSize(float size) {
        if (mTextSize != size) {
            mTextSize = size;

            if (mAdapter != null) {
                mAdapter.setTextSize(size);
            }
        }
    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        callLoadingListViewStartLoading(mAdapter == null);
        cancelTask();

        CommentTaskParam p = new CommentTaskParam();
        p.refresh = true;
        p.boardid = mBoardId;
        p.docid = mDocId;
        p.num = getLoadingNum();
        p.start = 0;
        p.top_p = mTopP;
        p.context = getActivity();
        mCommentTask = new CommentTask();
        mCommentTask.execute(p);
    }

    @Override
    protected void onHandleRefreshing(Object result) {
        super.onHandleRefreshing(result);

        mCommonReply.ready();

        List<Pair<String, List<Map<String, Object>>>> data = (List<Pair<String, List<Map<String, Object>>>>) result;
        
        List<Map<String, Object>> latest = (data != null && data.size() > 1 && data.get(1) != null) ? data
                .get(1).second : null;
        // 当有最新跟帖时显示加载更多
        if (latest != null && latest.size() >= getLoadingNum()) {
            callLoadingListViewAddMoreView();
        } else if (mAdapter == null || mAdapter.getCount() == 0) {
            callLoadingListViewRemoveMoreView();
        }
        
        boolean successed = data != null && data.size() != 0;
        if (successed) {
            StringUtil.updateRefreshTime(getActivity(), RERFESH_TAG);
            callLoadingListViewCompleteLoading(true, true);
            setData(data);
        } else {            
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoading(false, true);
        }
        if (mCallback != null) {
            mCallback.onCommentRefreshed(this, successed);
        }
    }

    @Override
    protected int canLoadingMore() {
        if (mData == null || mData.size() != 2) {
            // 这里返回非0表示不能加载,暂时返回100
            return 100;
        }
        return super.canLoadingMore();
    }

    @Override
    protected void onLoadingMore() {
        super.onLoadingMore();

        final int num = getLoadingNum();

        int start = (mData.get(1).second.size() == 0) ? 0 : getLoadingStart() + num;
        callLoadingListViewStartLoadingMore(start);

        CommentTaskParam p = new CommentTaskParam();
        p.boardid = mBoardId;
        p.docid = mDocId;
        p.num = num;
        p.start = start;
        p.context = getActivity();

        cancelTask();

        mCommentTask = new CommentTask();
        mCommentTask.execute(p);

    }

    @Override
    protected void onHandleLoadingMore(Object result) {
        super.onHandleLoadingMore(result);

        List<Map<String, Object>> data = (List<Map<String, Object>>) result;

        if (data == null) {
            //返回null说明已经网络错误,需要显示加载更多
            Toast.makeText(getActivity(), R.string.msg_loading_failed, Toast.LENGTH_SHORT).show();
            callLoadingListViewCompleteLoadingMore(false, true);
        } else if (data.size() == 0 || data.size() < getLoadingNum()) {
            // 返回数量为0或者小于getLoadingNum(),说明已经加载完,不需要显示加载更多
            callLoadingListViewCompleteLoadingMore(true, false);
            addData(data);
            callLoadingListViewRemoveMoreView();
        } else {
            // 返回数量为0或者小于getLoadingNum(),说明还没加载完,需要显示加载更多
            callLoadingListViewCompleteLoadingMore(true, true);
            addData(data);
        }
    }

    private void setData(List<Pair<String, List<Map<String, Object>>>> data) {
        if (data != null && data.size() > 0) {
            List<Pair<String, List<Map<String, Object>>>> newData = new ArrayList<Pair<String, List<Map<String, Object>>>>();
            for (Pair<String, List<Map<String, Object>>> pair : data) {
                if (pair.second == null) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    newData.add(Pair.create(pair.first, list));
                } else {
                    newData.add(pair);
                }
            }
            mData = newData;
            mAdapter = new CommonCommentAdapter(getActivity(), mData, mBoardId);
            mAdapter.setTextSize(mTextSize);
            mListView.setAdapter(mAdapter);
        }
    }

    private void addData(List<Map<String, Object>> data) {
        if (data == null || data.size() == 0 || mData == null || mData.size() < 2) {
            return;
        }

        Pair<String, List<Map<String, Object>>> p = mData.get(1);

        p.second.addAll(data);
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onReplyAction(CommonReply commonReply, int action) {
        switch (action) {
            case CommonReply.ACTION_SHARE: {
                String title = getActivity().getTitle().toString();
                String bi = mBoardId;
                String docid = mDocId;
                String docTitle = mDocTitle;
                ShareUtil.showShareDialog(getActivity(), title, bi, docid, docTitle);
                break;
            }
            case CommonReply.ACTION_COLLECTED: {
                long id = mCollectUtil.doCollectObject(mCommentUrl, mDocTitle, "1", mCollectType);
                mCommentCollectId = -1;
                if (id != -1) {
                    mCommentCollectId = mCollectUtil.getAlreadyCollect(mCommentUrl, "1",
                            mCollectType);
                }

                if (mCommentCollectId == -1) {
                    commonReply.setCollected(false);
                    Toast.makeText(getActivity(), R.string.fail_collect, Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), R.string.success_collect, Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            }
            case CommonReply.ACTION_UNCOLLECTED: {
                if (mCommentCollectId != -1) {
                    mCollectUtil.deleteAlreadyCollect(mCommentCollectId, mCollectType);
                    mCommentCollectId = -1;
                    Toast.makeText(getActivity(), R.string.cancel_collect, Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            }
            case CommonReply.ACTION_REPLY: {
                String content = commonReply.getReplyContent();
                boolean replyWithQuote = false;
                String quote = null;

                Map<String, Object> lastFloor = (Map<String, Object>) commonReply.getEditTag();
                if (lastFloor != null) {
                    String p = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_P);
                    if (!TextUtils.isEmpty(p)) {
                        replyWithQuote = true;
                        if (p.contains(mDocId)) {
                            quote = p;
                        } else {
                            quote = mDocId + "_" + p;
                        }
                    }
                }

                replyComment(content, replyWithQuote, quote);
                break;
            }

            default:
                break;
        }

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (mCommonReply.dispatchKeyEvent(event)) {
            return true;
        }
        if (mToolPopup != null && mToolPopup.isShowing() && mToolPopup.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        ItemPosition itemPosition = mAdapter.getRealPosition(position);
        if (itemPosition.pos == -1) {
            return;
        }

        Map<String, Object> map = mAdapter.getChild(itemPosition.group, itemPosition.pos);

        if (map != null) {
            // 显示被顶次数
            int supportNum = getSupportNum(map);

            if (mToolPopup == null) {
                // 初始化工具条弹出框
                mToolPopup = new CommentToolsPopup(getActivity());
                mToolPopup.setContentView(R.layout.common_comment_toolbar);
                mToolPopup.setOnClickListener(this, new int[] {
                        R.id.share_text, R.id.reply_text, R.id.copy_text, R.id.support_text
                });
            }

            View v = mToolPopup.getContentView().findViewById(R.id.support_text);
            TextView supportText = (TextView) v.findViewById(R.id.tool_tv);
            supportText.setText(getResources().getString(R.string.support_comment, supportNum));
            v.setEnabled(true);

            mToolPopup.setTag(map);
            // mToolPopup.setAnimationStyle(0);
            // mToolPopup.showAsDropDown(adapterView, mToolPopupX, mToolPopupY
            // - adapterView.getHeight());
            // int totalHeight =
            // getResources().getDisplayMetrics().heightPixels;
            int height = (int) (getResources().getDisplayMetrics().density * 90);
            mToolPopup.showAtLocation(adapterView, Gravity.NO_GRAVITY, mToolPopupX, mToolPopupY
                    - height);
        }

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
          if (mCommonReply != null) {
              mCommonReply.finishEdit();
          }
        } else if (action == MotionEvent.ACTION_UP) {
            if (mToolPopup != null && mToolPopup.isHide()) {
                mToolPopup.dismiss();
                return true;
            }
            mToolPopupX = (int) event.getRawX();
            mToolPopupY = (int) event.getRawY();
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (mToolPopup != null && mToolPopup.isShowing() && dispatchToolPopupClick(id)) {
            return;
        }
    }

    private boolean dispatchToolPopupClick(int id) {
        boolean ret = true;
        boolean dismiss = true;
        switch (id) {
            case R.id.support_text: {
                dismiss = false;
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                addSupport(map);
                int supportNum = getSupportNum(map);

                View v = mToolPopup.getContentView().findViewById(R.id.support_text);
                TextView supportText = (TextView) v.findViewById(R.id.tool_tv);
                supportText.setText(getResources().getString(R.string.support_comment, supportNum));
                v.setEnabled(false);

                View addone = mToolPopup.getContentView().findViewById(R.id.addone);
                addone.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.addone));

                int last = getLastFloorNum(map);
                if (last <= 0) {
                    break;
                }

                Map<String, Object> lastFloor = getFloor(map, last);

                final String boardid = mBoardId;
                final String docid = mDocId;
                final String p = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_P);
                new Thread() {
                    public void run() {
                        if (TextUtils.isEmpty(boardid) || TextUtils.isEmpty(docid)
                                || TextUtils.isEmpty(p)) {
                            return;
                        }
                        GetComments.upVote(boardid, docid, p, getActivity());
                    }
                }.start();
                break;
            }
            case R.id.share_text: {
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                int last = getLastFloorNum(map);
                if (last <= 0) {
                    break;
                }

                Map<String, Object> lastFloor = getFloor(map, last);

                String title = getActivity().getTitle().toString();
                String bi = mBoardId;
                String docid = mDocId;
                String p = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_P);
                String docTitle = mDocTitle;

                ShareUtil.showShareDialog(getActivity(), title, bi, docid, p, docTitle);

                break;
            }
            case R.id.reply_text: {
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                int last = getLastFloorNum(map);
                if (last <= 0) {
                    break;
                }

                Map<String, Object> lastFloor = getFloor(map, last);
                mCommonReply.beginEdit(lastFloor);
                break;
            }
            case R.id.copy_text: {
                Map<String, Object> map = (Map<String, Object>) mToolPopup.getTag();
                int last = getLastFloorNum(map);
                if (last <= 0) {
                    break;
                }

                StringBuilder sb = new StringBuilder();
                boolean isfault = false;
                for (int i = 1; i <= last; i++) {
                    Map<String, Object> item = getFloor(map, i);
                    if (item == null) {
                        if(!isfault){
                            if (i > 1) {
                                sb.append("||...");
                            }
                            isfault = true;
                        }
                        continue;
                    }
                    if (i > 1) {
                        sb.append("||");
                    }
                    if (last > 1) {
                        sb.append(i).append("楼:");
                    }
                    sb.append((String) ModelUtils.getValue(item, Comment.PARAM_B));
                }

                Tools.copyText(getActivity(), sb.toString());
                break;
            }
            default:
                ret = false;
                break;
        }
        if (ret && dismiss) {
            mToolPopup.dismiss();
        }
        return ret;
    }

    /**
     * 获取最后楼层标识
     * 
     * @param map
     * @return
     */
    private int getLastFloorNum(Map<String, Object> map) {
        if (map == null || mAdapter == null) {
            return -1;
        }
        int last = mAdapter.getLastFloorNum(map);
        if (last <= 0) {
            return -1;
        }
        return last;
    }

    /**
     * 获取跟帖中某一楼层的数据
     * 
     * @param map
     * @param num
     * @return
     */
    private Map<String, Object> getFloor(Map<String, Object> map, int num) {
        return (Map<String, Object>) ModelUtils.getValue(map, String.valueOf(num));
    }

    /**
     * 获取跟帖被顶次数
     * 
     * @param map
     * @return
     */
    private int getSupportNum(Map<String, Object> map) {
        // 从最后一层取出被顶次数
        int supportNum = 0;
        int last = getLastFloorNum(map);
        if (last > 0) {
            try {
                Map<String, Object> lastFloor = getFloor(map, last);
                String str = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_V);
                supportNum = Integer.valueOf(str);
            } catch (Exception e) {
                supportNum = 0;
            }
        }
        return supportNum;
    }

    /**
     * 增加被顶次数
     * 
     * @param map
     */
    private void addSupport(Map<String, Object> map) {
        int supportNum = 0;
        int last = getLastFloorNum(map);
        Map<String, Object> lastFloor = null;
        if (last > 0) {
            try {
                lastFloor = getFloor(map, last);
                String str = (String) ModelUtils.getValue(lastFloor, Comment.PARAM_V);
                supportNum = Integer.valueOf(str);
            } catch (Exception e) {
                supportNum = 0;
            }
        }

        if (lastFloor != null) {
            lastFloor.put(Comment.PARAM_V, String.valueOf(supportNum + 1));
        }
    }

    private void replyComment(String content, boolean replyWithQuote, String quote) {
        Context context = getActivity();

        if (TextUtils.isEmpty(content)) {
            Toast.makeText(context, "不能发空消息", Toast.LENGTH_SHORT).show();
            return;
        } else if (content.length() <= 1 || content.length() > 1000) {
            Toast.makeText(context, "回复请在2-1000字内", Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences set_prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String account = set_prefs.getString("account", "");

        if (TextUtils.isEmpty(account)) {
            Intent Loginintent = new Intent(context, AccountLogin.class);
            Loginintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Bundle bundle = new Bundle();

            bundle.putBoolean("isreply", true);
            bundle.putBoolean("replyWithQuote", replyWithQuote);

            bundle.putString("replydocid", mDocId);
            bundle.putString("replyquote", quote);
            bundle.putString("replyBoard", mBoardId);
            bundle.putString("replycontent", content);
            Loginintent.putExtras(bundle);
            context.startActivity(Loginintent);
        } else {
            ReplyCommentTaskParam p = new ReplyCommentTaskParam();
            p.boardid = mBoardId;
            p.docid = mDocId;
            p.quote = quote;
            p.content = content;
            p.account = account;
            p.replyWithQuote = replyWithQuote;
            p.context = getActivity();
            cancelReplyCommentTask();

            if (mProgressDialog == null) {
                mProgressDialog = new ProgressDialog(getActivity());
                mProgressDialog.setMessage("正在发表跟贴...");
                mProgressDialog.setCancelable(true);

                mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        cancelReplyCommentTask();
                    }
                });
            }
            mProgressDialog.show();
            mReplyCommentTask = new ReplyCommentTask();
            mReplyCommentTask.execute(p);

        }
    }

    private void cancelReplyCommentTask() {
        if (mReplyCommentTask != null && !mReplyCommentTask.isCancelled()) {
            mReplyCommentTask.cancel(true);
            mReplyCommentTask = null;
        }
        mCommonReply.finishEdit();
        dismissProgressDialog();
    }

    @Override
    public void onApplyTheme() {
        super.onApplyTheme();

        ThemeSettingsHelper themeSettingsHelper = getThemeSettingsHelper();
        Context context = getActivity();

        if (mCommonReply != null) {
            mCommonReply.onApplyTheme(context, themeSettingsHelper);
        }
    }

    /**
     * 回复跟帖任务
     * 
     * @author wjying
     */
    private class ReplyCommentTask extends AsyncTask<ReplyCommentTaskParam, Object, Object> {

        @Override
        protected Object doInBackground(ReplyCommentTaskParam... params) {
            if (params == null || params.length == 0 || params[0] == null) {
                return null;
            }

            

            ReplyCommentTaskParam p = params[0];
            String boardid = p.boardid;
            String docid = p.docid;
            String account = p.account;
            String content = p.content;
            boolean replyWithQuote = p.replyWithQuote;
            String quote = p.quote;
            Context context = p.context;
            
            String result;
            if (replyWithQuote) {
                result = GetComments.postComment(boardid, docid, quote, content, account,
                        "新闻客户端用户", "0.0.0.0", "false", context);
            } else {
                result = GetComments.postComment(boardid, docid, content, account, "新闻客户端用户",
                        "0.0.0.0", "false", context);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);
            mCommonReply.finishEdit();
            dismissProgressDialog();
            if (isCancelled() || result == null || !isAdded()) {
                return;
            }

            String ret = (String) result;
            if ("1".equals(ret)) {
                Toast.makeText(getActivity(), "发表成功", Toast.LENGTH_SHORT).show();
            } else if (TextUtils.isEmpty(ret)) {
                Toast.makeText(getActivity(), "发表失败", Toast.LENGTH_SHORT).show();
            } else {
                ret = ret.toLowerCase();

                if (ret.contains("postdata")) {
                    ret = "内容含有非法字符";
                }

                Toast.makeText(getActivity(), "发表失败" /*，原因:" + ret*/, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private class ReplyCommentTaskParam {
        String boardid;

        String docid;

        String account;

        String content;

        boolean replyWithQuote;

        String quote;

        int type;
        
        Context context;
    }

    /**
     * 取跟帖任务
     * 
     * @author wjying
     */
    private class CommentTask extends AsyncTask<CommentTaskParam, Object, Object> {

        @Override
        protected Object doInBackground(CommentTaskParam... params) {
            if (params == null || params.length == 0 || params[0] == null) {
                return null;
            }

            CommentTaskParam p = params[0];
            String boardid = p.boardid;
            String docid = p.docid;
            int start = p.start;
            int num = p.num;
            int hide = p.hide;
            int hideStart = p.hideStart;
            int hideEnd = p.hideEnd;
            Context context = p.context;

            List<Pair<String, List<Map<String, Object>>>> data = new ArrayList<Pair<String, List<Map<String, Object>>>>();
            
            if (p.refresh) {
                List<Map<String, Object>> list = null;
                if (!TextUtils.isEmpty(p.top_p)) {
                    Map<String, Object> hot = Comment.expand(boardid, docid, p.top_p, context);
                    if (hot.size() > 0) {
                        list = new ArrayList<Map<String, Object>>();
                        list.add(hot);
                    }
                } else {
                    Map<String, Object> hot = HotComment.getHotComment(context, boardid, docid, 0,
                            5, 10, 2, 2);
                    list = (List<Map<String, Object>>) ModelUtils.getValue(hot,
                            HotComment.PARAM_HOTPOSTS);
                }
                if (list == null) {
                    list = new ArrayList<Map<String, Object>>();
                }
                Pair<String, List<Map<String, Object>>> pair = Pair.create(TextUtils.isEmpty(p.top_p) ? TAG_HOT : TAG_TOP, list);
                data.add(pair);
            }
            

            Map<String, Object> latest = LatestComment.getLatestComment(context, boardid,
                    docid, start, num, hide, hideStart, hideEnd);
            List<Map<String, Object>> list = (List<Map<String, Object>>) ModelUtils.getValue(
                    latest, LatestComment.PARAM_NEWPOSTS);
            if (latest != null && list == null) {
                list = new ArrayList<Map<String, Object>>();
            }

            Pair<String, List<Map<String, Object>>> pair = Pair.create(TAG_LATEST, list);
            data.add(pair);

            return data;
        }

        @Override
        protected void onPostExecute(Object result) {
            super.onPostExecute(result);

            if (isCancelled() || !isAdded()) {
                return;
            }
            
            List<Pair<String, List<Map<String, Object>>>> data = (List<Pair<String, List<Map<String, Object>>>>) result;

            Handler handler = getHandler();
            if (data.size() == 2) {
                Message msg = handler.obtainMessage(MSG_REFRESHING);
                msg.obj = data;
                handler.sendMessage(msg);
            } else if (data.size() == 1) {
                Message msg = handler.obtainMessage(MSG_LOADING_MORE);
                msg.obj = data.get(0).second;
                handler.sendMessage(msg);
            }
        }
    }

    private class CommentTaskParam {
        String boardid;

        String docid;

        String top_p;

        int start;

        int num;

        int hide = 10;

        int hideStart = 2;

        int hideEnd = 2;
        
        Context context;

        boolean refresh;
    }

    public interface CommentCallback {
        public void onCommentRefreshed(CommentFragment fragment, boolean successed);
    }
}
